package main

import (
	"context"
	"fmt"

	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/rest"

	//"k8s.io/apimachinery/pkg/runtime/schema"
	"k8s.io/client-go/tools/clientcmd"
)

/*
*
@Author: cloudea
@Desc:  获取kube-system下的pod列表
*/
func main() {
	/** 1. 加载配置文件，生成配置对象 */
	config, err := clientcmd.BuildConfigFromFlags("", "/home/cloudea/.kube/config")
	if err != nil {
		panic(err.Error())
	}

	// pods, /api/v1/pods
	// deployments, /apis/apps/v1/namespaces/{ns}/deployments/{deployment}
	/** 2. 配置API路径 */
	config.APIPath = "api"
	/** 3. 配置分组版本 */
	config.GroupVersion = &corev1.SchemeGroupVersion // 无名资源组, group: "", version: "v1"

	/** 4. 配置编解码文件 */
	config.NegotiatedSerializer = scheme.Codecs

	/** 实例化rest client*/

	restclient, err := rest.RESTClientFor(config)
	if err != nil {
		panic(err.Error())
	}

	result := &corev1.PodList{}
	err = restclient.
		Get(). // 返回一个request对象，后面是对该对象的配置
		Namespace("kube-system").
		Resource("pods").
		VersionedParams(&metav1.ListOptions{}, metav1.ParameterCodec).
		Do(context.TODO()). //触发请求
		Into(result)
	// restclient.Get();
	// restclient.Delete();
	// restclient.Patch();
	// restclient.Post();
	// restclient.Put();
	// restclient.Verb();
	// restclient.GetRateLimiter();
	// restclient.APIVersion();

	if err != nil {
		panic(err.Error())
	}

	for _, item := range result.Items {
		fmt.Println(item.Name)
	}
}
